﻿using DMS.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace DMS.Utils
{
    public class Security
    {
        public const string UserRoleAdmin = "admin";
        private readonly BUS.Bus _bo = new BUS.Bus();


        public void SetAuthCookie(HttpContext httpContext, FormsAuthenticationTicket authenticationTicket, string CookieName)
        {
            var encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);
            //FormsAuthentication.SetAuthCookie(encryptedTicket, false);
            var cookie = new HttpCookie(CookieName, encryptedTicket);
            cookie.HttpOnly = true;
            cookie.Expires = authenticationTicket.Expiration;
            httpContext.Response.Cookies.Add(cookie);
        }

        public void UserSignIn(AccountObject accountInfo, HttpContext _curentHttpContext)
        {
            var loginToken = new FormsAuthenticationTicket(1, ConstKey.SignInToken, DateTime.Now, DateTime.Now.AddHours(1),
                true, JsonConvert.SerializeObject(accountInfo));
            SetAuthCookie(_curentHttpContext, loginToken, ConstKey.SignInToken);

        }

        public bool CheckLogin(HttpContext _curentHttpContext)
        {
            var LoginTokenCookie = _curentHttpContext.Request.Cookies[ConstKey.SignInToken];
            if (LoginTokenCookie != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public AccountObject CurrentUser(HttpContext _curentHttpContext)
        {
            AccountObject userApp = null;
            var LoginTokenCookie = _curentHttpContext.Request.Cookies[ConstKey.SignInToken];
            if (LoginTokenCookie != null)
            {
                try
                {
                    var token = FormsAuthentication.Decrypt(LoginTokenCookie.Value);
                    userApp = JsonConvert.DeserializeObject<AccountObject>(token.UserData);

                }
                catch
                {
                    return null;
                }
            }
            return userApp;
        }
        public void SignOutLocal(HttpContext httpContext)
        {
            var cookie = new HttpCookie(ConstKey.SignInToken);
            DateTime nowDateTime = DateTime.Now;
            cookie.Expires = nowDateTime.AddDays(-1);
            httpContext.Response.Cookies.Add(cookie);
            FormsAuthentication.SignOut();
        }

        public void SignOutLocal()
        {
            FormsAuthentication.SignOut();
        }

    }
}